package com.shengqin.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shengqin.entity.SummaryArchive;
import com.shengqin.entity.TempExport;
import com.shengqin.entity.TestResult;
import com.shengqin.pojo.summary.ProjectItem;
import com.shengqin.service.ISummaryArchiveService;
import com.shengqin.service.ITempExportService;
import com.shengqin.utils.CustomCellWriteWidthConfig;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/")
public class TempExportController {

    @Resource
    private ITempExportService tempExportService;
    @Resource
    private ISummaryArchiveService summaryArchiveService;

    private final List<String> excelFixHeaders = new ArrayList<>();

    @PostConstruct
    public void init() {
        excelFixHeaders.add("学号");
        excelFixHeaders.add("姓名");
        excelFixHeaders.add("性别");
        excelFixHeaders.add("出生日期");
        excelFixHeaders.add("身份证号");
        excelFixHeaders.add("ZYMC");
        excelFixHeaders.add("FY");
        excelFixHeaders.add("BH");
        for (int i = 1; i <= 4; i++) {
            excelFixHeaders.add("身高" + i);
            excelFixHeaders.add("体重" + i);
            excelFixHeaders.add("肺活量" + i);
            excelFixHeaders.add("50米跑" + i);
            excelFixHeaders.add("1000米或800米" + i);
            excelFixHeaders.add("坐位体前屈" + i);
            excelFixHeaders.add("立定跳远" + i);
            excelFixHeaders.add("引体向上或一分钟仰卧起坐" + i);
            excelFixHeaders.add("分数" + i);
            excelFixHeaders.add("评价" + i);
        }
        excelFixHeaders.add("总分");
    }

    private List<List<String>> buildExcelHeads() {

        List<List<String>> headers = new ArrayList<>();
        for (String excelFixHeader : excelFixHeaders) {
            List<String> head = new ArrayList<>();
            head.add(excelFixHeader);
            headers.add(head);
        }

        List<String> head = new ArrayList<>();
        head.add("总分");
        headers.add(head);

        return headers;
    }

    @GetMapping("/exportTemp")
    public void exportTemp() {
        Page<TempExport> tempExportPage = new Page<>(1, 5000);
        tempExportService.page(tempExportPage);
        List<TempExport> tempExportList = tempExportPage.getRecords();
        Set<String> tempKeys = new HashSet<>();
        for (TempExport tempExport : tempExportList) {
            tempKeys.add(tempExport.getName() + "_" + tempExport.getBirthday());
        }
        List<SummaryArchive> summaryArchiveList =  summaryArchiveService.listByTempUniqKeys(tempKeys);

        Map<String,List<SummaryArchive>> summaryArchiveMap = summaryArchiveList.stream().collect(Collectors.groupingBy(SummaryArchive::getTempUniqKey));

        List<List<Object>> dataList = new ArrayList<>();
        tempExportList.forEach(tempExport -> {
            String tempUniqKey = tempExport.getName() + "_" + tempExport.getBirthday();
            List<SummaryArchive> summaryArchives = summaryArchiveMap.get(tempUniqKey);
            List<Object> data = new ArrayList<>();
            data.add(tempExport.getStdCode());
            data.add(tempExport.getName());
            data.add(tempExport.getSex());
            data.add(tempExport.getBirthday());
            data.add(tempExport.getCardNumber());
            data.add(tempExport.getZymc());
            data.add(tempExport.getFy());
            data.add(tempExport.getBh());
            List<ProjectItem> projectItems = new ArrayList<>();
            for (int i = 1; i <= 4; i++) {
                ProjectItem projectItem = new ProjectItem();
                if(!CollectionUtils.isEmpty(summaryArchives)){
                    int finalI = i;
                    summaryArchives.stream().sorted(Comparator.comparing(SummaryArchive::getId)).forEach(summaryArchive -> {
                        boolean isSetValue1 = summaryArchive.getSchoolYear().equals("2020") && finalI == 1;
                        boolean isSetValue2 = summaryArchive.getSchoolYear().equals("2021") && finalI == 2;
                        boolean isSetValue3 = summaryArchive.getSchoolYear().equals("2022") && finalI == 3;
                        boolean isSetValue4 = summaryArchive.getSchoolYear().equals("2023") && finalI == 4;
                        if(!CollectionUtils.isEmpty(summaryArchive.getTestResultList())){
                            if(isSetValue1 || isSetValue2 || isSetValue3 || isSetValue4){
                                AtomicReference<BigDecimal> finalScore = new AtomicReference<>(BigDecimal.ZERO);
                                summaryArchive.getTestResultList().forEach(testResult -> {
                                    getTestResult(testResult, projectItem);
                                    if (testResult.getFinalScore() != null) {
                                        finalScore.set(finalScore.get().add(testResult.getFinalScore()));
                                    }
                                });
                                projectItem.setTotalScore(finalScore.get());
                            }
                        }
                    });
                    tempExport.setProjectItems(projectItems);
                }
                projectItems.add(projectItem);
            }
            projectItems.forEach(projectItem -> {
                data.add(projectItem.getHeight());
                data.add(projectItem.getWeight());
                data.add(projectItem.getVital());
                data.add(projectItem.getRun50());
                data.add(projectItem.getRun800Or1000());
                data.add(projectItem.getSiteUp());
                data.add(projectItem.getStandJump());
                data.add(projectItem.getPullUp());
                data.add(projectItem.getTotalScore());
                data.add("");
            });
            dataList.add(data);
        });

        File file = new File("D://test.xlsx");

        EasyExcel.write(file)
                // 这里放入动态头
                .head(buildExcelHeads())
                .registerWriteHandler(new CustomCellWriteWidthConfig()).sheet("sheet1").doWrite(dataList);
    }



    private void getTestResult(TestResult testResult, ProjectItem projectItem){
        switch (testResult.getPrjName()) {
            case "身高":
                projectItem.setHeight(testResult.getResult());
                break;
            case "体重":
                projectItem.setWeight(testResult.getResult());
                break;
            case "肺活量":
                projectItem.setVital(testResult.getResult());
                break;
            case "50米跑":
                projectItem.setRun50(testResult.getResult());
                break;
            case "800米":
            case "1000米":
                projectItem.setRun800Or1000(testResult.getResult());
                break;
            case "坐位体前屈":
                projectItem.setSiteUp(testResult.getResult());
                break;
            case "立定跳远":
                projectItem.setStandJump(testResult.getResult());
                break;
            case "引体向上":
            case "一分钟仰卧起坐":
                projectItem.setPullUp(testResult.getResult());
                break;
        }
    }
}
